# encoding: utf-8
class RepliesController < ApplicationController
  before_filter :authenticate_user!
  before_filter :is_owner_of_reply?, :only => [:edit, :update]
  before_filter :is_member_of_project?
  before_filter :get_project, :only => [:new, :edit, :create, :update]
  before_filter :get_topic, :only => [:new, :edit, :create, :update]

  def new
    @reply = Reply.new
    
    respond_to do |format|
      format.html
      format.xml  { render :xml => @reply }
    end
  end

  def edit
    @reply = Reply.find(params[:id])
  end

  def create
    @reply = Reply.new(params[:reply])
    @reply.topic_id = params[:topic_id]
    @reply.user_id = current_user.id

    respond_to do |format|
      if @reply.save
        flash[:notice] = t :reply_create_success, :scope => [:flash, :notice]
        format.html { params[:bug_id].nil? ? redirect_to(project_topic_path(params[:project_id], params[:topic_id])) : redirect_to(project_bug_path(params[:project_id], params[:bug_id])) }
        format.xml  { render :xml => @reply, :status => :created, :location => @reply }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @reply.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @reply = Reply.find(params[:id])

    respond_to do |format|
      if @reply.update_attributes(params[:reply])
        flash[:notice] = t :reply_edit_success, :scope => [:flash, :notice]
        format.html { params[:bug_id].nil? ? redirect_to(project_topic_path(params[:project_id], params[:topic_id])) : redirect_to(project_bug_path(params[:project_id], params[:bug_id])) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @reply.errors, :status => :unprocessable_entity }
      end
    end
  end

  private
  def is_owner_of_reply?
    unless(Reply.find(params[:id]).user_id == current_user.id)
      flash[:error] = t :reply_no_right, :scope => [:flash, :error]
      redirect_to project_topic_path(params[:project_id], params[:topic_id])
    end
  end
end
